package jp.reflexworks.gae.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.google.appengine.api.datastore.Query;

public class QueryUtils {

	private String[] indexList;

	/**
	 * @param indexList indexが張られている検索対象項目
	 */
	public QueryUtils(String[] indexList) {
		this.indexList = indexList;
	}

	/**
	 * 検索条件をQueryオブジェクトに設定します
	 * @param param 検索条件
	 * @param query Query
	 */
	public void setParam(Object param, Query query) {
		Field[] fields = param.getClass().getDeclaredFields();

		for (Field fld : fields) {
			if (isIndex(fld)) {
				try {
					String fieldName = fld.getName();
					String getter = "get" + fld.getName().substring(0,1).toUpperCase() + fld.getName().substring(1);
					Object propvalue = this.getValue(param, getter);

					if (propvalue != null) {
						query.addFilter(fieldName, Query.FilterOperator.EQUAL, propvalue);
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private boolean isIndex(Field fld) {
		String fieldName = fld.getName();
		if (fieldName != null) {
			for (String index : indexList) {
				if (fieldName.equals(index)) {
					return true;
				}
			}
		}
		return false;
	}

	public Object getValue(Object source, String getter) {

		Method method = null;
		Object ret = null;

		try {
			method = source.getClass().getMethod(getter);
			ret = method.invoke(source);

		} catch (SecurityException e2) {
			// Do Nothing
		} catch (NoSuchMethodException e2) {
			// Do Nothing
		} catch (IllegalArgumentException e) {
			// Do Nothing
		} catch (IllegalAccessException e) {
			// Do Nothing
		} catch (InvocationTargetException e) {
			// Do Nothing
		}

		return ret;
	}

}
